package com.omenkk.juc.AQS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock {
    private MySync sync = new MySync();



    @Override
    public void lock() {

        //这个方法是AQS的方法，不成功进入等待队列
    sync.acquire(1);

        /**
         * 调用了 tryAcquire,我们可以通过 extends AbstractQueuedSynchronizer改写逻辑,失败后,线程会被加入 CLH 队列，并可能被挂起
         *   public final void acquire(int arg) {
         *         if (!tryAcquire(arg))
         *             acquire(null, arg, false, false, false, 0L);
         *     }
         */
    }

    //尝试，不成功，  进入等待队列，可以被打断   不成功后续逻辑由AQS 的 tryAcquireNanos(long nanosTimeout)方法处理
    @Override
    public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
    }

    //我们重写了这个方法，如果获取失败，直接返回false
    @Override
    public boolean tryLock() {
       return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.tryRelease(1);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }
}
